// Fill out your copyright notice in the Description page of Project Settings.


#include "MyBlueprintAsyncActionBase.h"
#include "TimerManager.h"

UMyBlueprintAsyncActionBase* UMyBlueprintAsyncActionBase::WaitTickTestActorCounter(UObject* WorldContextObject, ATickTestActor* Actor, int32 TargetCounter)
{
    UMyBlueprintAsyncActionBase* Node = NewObject<UMyBlueprintAsyncActionBase>();
    auto Check = [Node, WorldContextObject, Actor, TargetCounter]() {
        if (IsValid(Actor))
        {
            if (Actor->Counter >= TargetCounter)
            {
                UE_LOG(LogTemp, Log, TEXT(__FUNCTION__"@%u wait TargetCounter(%d) success. Current Counter=[%d]."), __LINE__, TargetCounter, Actor->Counter);
                Node->OnSuccess.Broadcast(Actor->Counter);
                WorldContextObject->GetWorld()->GetTimerManager().ClearTimer(Node->TimerHandle);
            }
            else
            {
                UE_LOG(LogTemp, Log, TEXT(__FUNCTION__"@%u waiting TargetCounter(%d)... Current Counter=[%d]."), __LINE__, TargetCounter, Actor->Counter);
            }
        }
        else
        {
            UE_LOG(LogTemp, Log, TEXT(__FUNCTION__"@%u wait fail. Actor is invalid."), __LINE__);
            Node->OnFail.Broadcast(-1);
            WorldContextObject->GetWorld()->GetTimerManager().ClearTimer(Node->TimerHandle);
        }
    };
    WorldContextObject->GetWorld()->GetTimerManager().SetTimer(Node->TimerHandle, FTimerDelegate::CreateLambda(Check), 0.1f, true);
    UE_LOG(LogTemp, Log, TEXT(__FUNCTION__"@%u wait TargetCounter(%d) begin."), __LINE__, TargetCounter);
    return Node;
}
